﻿using ExtensionsAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BleQua.Extensions {
	public class Extension : IExtension {
		public Extension(string AssemblyPath, string ExtensionType) {
			this.AssemblyPath = AssemblyPath;
			this.ExtensionTypeName = ExtensionType;

			System.Reflection.Assembly pluginAssembly = System.Reflection.Assembly.LoadFrom(AssemblyPath);
			this.ExtensionType = pluginAssembly.GetType(ExtensionTypeName);
		}

		public string AssemblyPath { get; private set; }
		public string ExtensionTypeName { get; private set; }
		public Type ExtensionType { get; private set; }
		public IEnumerable<Type> InterfaceTypes { get { return this.ExtensionType.GetInterfaces( ); } }

		public T CreateInstace<T>( ) where T : IExtensionBase {
			//Create a new assembly from the plugin file we're adding..
			if (this.ExtensionType == null) {
				System.Reflection.Assembly pluginAssembly = System.Reflection.Assembly.LoadFrom(AssemblyPath);
				this.ExtensionType = pluginAssembly.GetType(ExtensionTypeName);
			}
			if (ExtensionType != null && ExtensionType.IsPublic && !ExtensionType.IsAbstract) {
				Type interfaceType = ExtensionType.GetInterface(typeof(T).FullName);
				if (this.InterfaceTypes.Contains(typeof(T))) {
					return (T)Activator.CreateInstance(ExtensionType);
				}
			}
			return default(T);
		}

		public void Dispose( ) {
			//throw new NotImplementedException( );
		}
	}
}
